// /src/store/useLanguageStore.ts
import { create } from 'zustand';
import { persist, PersistStorage } from 'zustand/middleware';
import Taro from '@tarojs/taro';
import { changeLanguage as i18nChangeLanguage } from '@/utils/i18n';

interface LanguageState {
  language: string;
  setLanguage: (lang: string) => void;
}

const uniStorage: PersistStorage<any> = {
  setItem: (name: string, value: any) => {
    Taro.setStorageSync(name, value);
  },
  getItem: (name: string) => {
    const value = Taro.getStorageSync(name);
    // 注意：zustand 存的是字符串，需要原样返回
    return value ?? null;
  },
  removeItem: (name: string) => {
    Taro.removeStorageSync(name);
  },
};

// 创建持久化的语言 Store
export const useLanguageStore = create<LanguageState>()(
  persist(
    set => ({
      language: 'en', // 初始值（会被 persist 恢复覆盖）
      setLanguage: (lang: string) => {
        i18nChangeLanguage(lang); // 触发 i18next 切换
        set({ language: lang }); // 更新 Zustand 状态
      },
    }),
    {
      name: 'language-storage', // 存储名
      storage: uniStorage,
    }
  )
);
